const { escape } = require('mysql')
const {executeQuery} = require('../config/db_config')
const express = require('express')
let userRouter = express.Router()
userRouter.use(express.json())
const sessionManager = require('../utils/sessionManager');
const emailService = require('../utils/emailService');

userRouter.delete('/',async (req,resp)=>{
  const sql = `delete from user where id=${req.query.id}`
  const res = await executeQuery(sql)
  resp.send({
    code:200,
    message:'success',
    data:[]
  })
})

userRouter.post("/",async (req,resp)=>{
  const sql = `insert into user(username,password) values(${escape(req.body.data.username)},${escape(req.body.data.password)})`
  const res = await executeQuery(sql)
  resp.send({
    code:200,
    message:'success',
    data:[]
  })
})

userRouter.put("/",async (req,resp)=>{
  console.log(req.body.data)
  const res = await executeQuery(`select * from user where id=${req.body.data.id}`)
  if(res.length==0){
    resp.send({
      code:502,
      message:'user_not_exist',
    })
  }else{
    if(res[0].password==req.body.data.pwd){
      if(res[0].password==req.body.data.nPwd){
        resp.send({
          code:502,
          message:'pwd is can not same',
        })
      }else{
        const sql = `update user set password=${escape(req.body.data.nPwd)} where id=${req.body.data.id}`
        await executeQuery(sql)
        req.session.destroy()
        resp.send({
          code:200,
          message:'success',
          data:[]
        })
      }
      
    }else{
      resp.send({
        code:502,
        message:'password_iccorect',
      })
    }
  }
})

userRouter.get("/logout",async (req,resp)=>{
  const token = req.headers['Authorization']?.split(' ')[1];
  await sessionManager.invalidateSession(token);
  
  req.session.destroy()
  resp.send({
    code:200,
    message:'success'
  })
})
userRouter.get("/",async (req,resp)=>{
  const key = req.query.key
  const limit = req.query.limit
  const startIndex = (req.query.now_page-1)*limit
  const sql = `select * from user where username like '%${key}%' limit ${startIndex},${limit}`
  const sql1 = `select count(*) as num from user where username like '%${key}%' limit ${startIndex},${limit}`
  const res = await executeQuery(sql)
  const res1 = await executeQuery(sql1)
  
  resp.send({
    code:200,
    message:'success',
    data:{
      total:res1[0].num,
      list:
      res.map((k)=>{
        return {
          id:k.id,
          role_id:k.role_id,
          role_name:k.role_name,
          username:k.username
        }
      })
    }
  })
})

userRouter.get("/login",async (req,resp)=>{
  const sql = `select * from user where username=${escape(req.query.username)} and password=${escape(req.query.password)}`
  const res = await executeQuery(sql)
  if(res.length==0){
    resp.send({
      code:502,
      message:'username or password is not icorrect',
      data:[]
    })
  }else{
    req.session.user_id=res[0].id
    const token = await sessionManager.createSession(res[0].id, req.ip);
    resp.send({
      code:200,
      message:'success',
      data:{
        user_id:res[0].id,
        role_id:res[0].role_id,
        username:res[0].username,
        token:token
      }
    })
  }
})

// 绑定邮箱
userRouter.post('/email/bind/confirm', async (req, resp) => {
    try {
      const { email, code, id } = req.body;
        if (!id) {
            return resp.status(401).send({
                code: 401,
                message: '未登录'
            });
        }

        // 验证验证码
        await emailService.verifyCode(email, code, 'bind');

        // 更新用户邮箱
        const sql = `update user set email = ${escape(email)} where id = ${id}`;
        await executeQuery(sql);

        resp.send({
            code: 200,
            message: '邮箱绑定成功'
        });
    } catch (error) {
        resp.status(400).send({
            code: 400,
            message: error.message
        });
    }
});

// 换绑邮箱
userRouter.post('/email/change/confirm', async (req, resp) => {
    try {
        const { email, code, id } = req.body;
        console.log(email,code,id)

        if (!id) {
            return resp.status(401).send({
                code: 401,
                message: '未登录'
            });
        }

        // 验证验证码
        await emailService.verifyCode(email, code, 'change');

        // 更新用户邮箱
        const sql = `update user set email = ${escape(email)} where id = ${id}`;
        await executeQuery(sql);

        resp.send({
            code: 200,
            message: '邮箱换绑成功'
        });
    } catch (error) {
        resp.status(400).send({
            code: 400,
            message: error.message
        });
    }
});

// 重置密码
userRouter.post('/email/resetPassword/confirm', async (req, resp) => {
    try {
        const { username, email, code, newPassword } = req.body;

        // 验证验证码
        await emailService.verifyCode(email, code, 'reset-password');

        // 更新用户密码
        const sql = `update user set password = ${escape(newPassword)} where username = ${escape(username)}`;
        await executeQuery(sql);

        resp.send({
            code: 200,
            message: '密码重置成功'
        });
    } catch (error) {
        resp.status(400).send({
            code: 400,
            message: error.message
        });
    }
});

module.exports={
  userRouter
}